// miniprogram/pages/termResult/termResult.js

const innerAudioInnerCtx = wx.createInnerAudioContext();
const {
  getFormatedDate
} = require("../../utils/fn");
import {
  asyncGetUsertermData,
  asyncAddUsertermData,
  asyncUpdateUsertermData,
} from "../../utils/usertermDataLib";

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    termDictList: [],
    analysisList: [],
    accuracyRate: "0%",
    correctAmount: 0,
    usertermData: {
      historyTermDict: {},
      errorTermDict: {},
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    const termDictListJson = options.termDictListJson;
    const termDictList = JSON.parse(termDictListJson);
    console.log(`34-34 termDictList: `, termDictList);
    this.setData({
      termDictList,
    });
    await this.updateAnalysis(termDictList);
  },

  async updateAnalysis(charDictList) {
    const submitTime = getFormatedDate();
    const openid = app.globalData.openid;
    console.log("41-41", asyncGetUsertermData, typeof (asyncGetUsertermData));
    const resData = await asyncGetUsertermData(openid);
    console.log("46-46 resData:", resData)
    const cloudUsertermDataRecord = resData.length > 0 ? resData[0] : {};
    console.log(`48-48 cloudUsertermDataRecord:`, cloudUsertermDataRecord);
    const cloudUsertermData = cloudUsertermDataRecord.usertermData;
    const errorTermDictKey = `usertermData.errorTermDict`;
    const historyTermDictKey = `usertermData.historyTermDict`;

    if (cloudUsertermData && cloudUsertermData.historyTermDict && cloudUsertermData.errorTermDict) {
      this.setData({
        [errorTermDictKey]: cloudUsertermData.errorTermDict,
        [historyTermDictKey]: cloudUsertermData.historyTermDict,
      });
    }
    // if(!usertermData){}
    let correctAmount = 0;
    // if (isFinished) {
    const historyTermDict = {};
    const errorTermDict = {};
    const analysisList = charDictList.map((charTerm, index) => {
      const userAnswerCharChar = charTerm.userAnswerCharChar;
      console.log(`64-64 userAnswerCharChar: `, userAnswerCharChar,  `charTerm: `, charTerm);
      const theAnswerCharChar = charTerm.curTermChar.char;
      let isCorrect = false;
      const tmpTerm = {...charTerm.curTermChar,submitTime};
      // tmpTerm.submitTime = submitTime;
      tmpTerm.userAnswerCharChar =  userAnswerCharChar ? userAnswerCharChar : "未答";
      console.log(`67-67 userAnswerCharChar == theAnswerCharChar: ${userAnswerCharChar} : ${theAnswerCharChar}`);
      console.log(`74-74 tmpTerm.userAnswerCharChar : ${tmpTerm.userAnswerCharChar}`);
      if (userAnswerCharChar == theAnswerCharChar) {
        correctAmount += 1;
        isCorrect = true;
      } else {
        errorTermDict[theAnswerCharChar] = tmpTerm;
      }
      historyTermDict[theAnswerCharChar] = tmpTerm;
      const pinyin = charTerm.curTermChar.pinyin;
      const voice = charTerm.curTermChar.voice;
      const analysis = {
        submitTime,
        userAnswerCharChar: tmpTerm.userAnswerCharChar,
        theAnswerCharChar,
        isCorrect,
        pinyin,
        voice,
      };
      return analysis;
    });
    const correctPercentNumber = Math.floor((correctAmount / this.data.termDictList.length)*1000)/10;
    const accuracyRate = `${correctPercentNumber}%`;

    this.setData({
      analysisList,
      accuracyRate,
      correctAmount,
      [errorTermDictKey]: errorTermDict,
      [historyTermDictKey]: historyTermDict,
    });
    console.log(`98-98 cloudUsertermData: `, cloudUsertermData);
    if(cloudUsertermData && cloudUsertermData.historyTermDict && cloudUsertermData.errorTermDict){
      asyncUpdateUsertermData(this.data.usertermData);
    }else{
      asyncAddUsertermData(this.data.usertermData);
    }

  },

  audioPlay: function (event) {
    console.log("40-40 event:", event)
    innerAudioInnerCtx.src = event.currentTarget.dataset.voice;
    // let audioCtx = wx.createAudioContext(audioid);
    console.log("43-43 voice:", innerAudioInnerCtx.src);
    innerAudioInnerCtx.play()
    // audioCtx = null;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})